<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="操作时间" prop="operateTime">
        <el-date-picker clearable
          v-model="queryParams.operateTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="住院号" prop="zyid">
        <el-input
          v-model="queryParams.zyid"
          placeholder="请输入住院号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:zyrecharge:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:zyrecharge:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="zyrechargeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="操作时间" align="center" prop="operateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="就诊卡号" align="center" prop="id" />
      <el-table-column label="住院号" align="center" prop="zyid" />
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column label="业务类型" align="center" prop="bizType" />
      <el-table-column label="充值方式" align="center" prop="payType" />
      <el-table-column label="充值金额" align="center" prop="amount" />
      <el-table-column label="充值状态" align="center" prop="payStatus" >
      <template #default="scope">
          <span :style="{ color: scope.row.payStatus === '已支付' ? 'green' : scope.row.payStatus === '未支付' ? 'red' : 'inherit' }">
            {{ scope.row.payStatus }}
          </span>
      </template>
      </el-table-column>
      <el-table-column label="卡内余额" align="center" prop="balance" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:zyrecharge:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:zyrecharge:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改住院充值记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-divider content-position="center">患者信息</el-divider>
      <el-form ref="zyrechargeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-select v-model="form.patientName" placeholder="请选择患者" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in patientsList" :key="index" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-input v-model="zjlx" disabled/>
        </el-form-item>
        <el-form-item label="微信昵称" >
          <el-input v-model="wxnc" disabled/>
        </el-form-item>
        <el-form-item label="就诊地址" >
          <el-input v-model="jzrdz" disabled/>
        </el-form-item>
        <el-form-item label="就诊卡号" prop="id">
          <el-input v-model="form.id" disabled/>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="zjhm" disabled/>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="sj" disabled/>
        </el-form-item>
        <div class="avatar-uploader">
          <!-- 文本内容 -->
          <span class="text">患者头像</span>

          <!-- 圆形相框 -->
          <div
              class="avatar-frame"
              @click="triggerFileInput"
          >
            <!-- 显示上传的头像或默认空白 -->
            <img
                v-if="avatarUrl"
                :src="avatarUrl"
                alt="用户头像"
                class="avatar-image"
            />
            <div v-else class="empty-frame">
            </div>

            <!-- 隐藏的文件输入 -->
            <input
                type="file"
                ref="fileInput"
                @change="handleFileChange"
                accept="image/*"
                style="display: none;"
            />
          </div>
        </div>

        <el-form-item label="关系" style="padding-top: 20px">
          <el-input v-model="gx"/>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">住院信息</el-divider>
      <el-form-item label="住院号" prop="zyid">
        <el-input v-model="form.zyid" placeholder="请输入住院号" />
      </el-form-item>
      <el-form-item label="住院状态">
        <el-input v-model="zyzt"  />
      </el-form-item>
      <el-form-item label="入院时间">
        <el-input v-model="rysj"/>
      </el-form-item>
      <el-form-item label="出院时间">
        <el-input v-model="cysj"/>
      </el-form-item>
      <el-form-item label="院区">
        <el-select v-model="form.hospitalArea" placeholder="请选择所属院区" clearable>
          <el-option
              v-for="area in hospitalAreaOptions"
              :key="area"
              :label="area"
              :value="area"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="住院科室">
        <el-select v-model="form.department" placeholder="请选择住院科室" clearable :disabled="!form.hospitalArea">
          <el-option
              v-for="dept in departmentOptions"
              :key="dept"
              :label="dept"
              :value="dept"
          />
        </el-select>
      </el-form-item>
      <el-divider content-position="center">订单信息</el-divider>
      <el-form ref="zyrechargeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="操作时间" prop="operateTime">
          <el-date-picker clearable
            v-model="form.operateTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择操作时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item label="充值方式" prop="payType">
          <el-input v-model="form.payType" placeholder="请输入充值方式" />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入充值金额" />
        </el-form-item>
        <el-form-item label="卡内余额" prop="balance">
          <el-input v-model="form.balance"  disabled/>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="form.payStatus">
            <el-radio
                v-for="(item, index) in status"
                :key="index"
                :label="item.label"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="业务类型" prop="bizType">
          <el-input v-model="form.bizType" placeholder="请输入业务类型" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="input" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup >
import { listZyrecharge, getZyrecharge, delZyrecharge, addZyrecharge, updateZyrecharge } from "@/api/system/zyrecharge"
import {
  listDepartments,
  getHospitalCampusName,
  getDepartmentNames,
  getDepartmentsByhospitalArea
} from "@/api/system/departments"
import {ref, watch} from "vue";
import {listPatients, getPatients, updatePatients} from "@/api/system/patients.js"

const { proxy } = getCurrentInstance()

const zyrechargeList = ref([])
const feeRecordsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const input =   ref('')
const gx = ref('本人')
const zjlx = ref('身份证号')
const wxnc = ref('')
const jzrdz = ref('')
const zjhm = ref('')
const sj = ref('')
const zyzt=ref('住院中')
const rysj=ref('2020/10/09 09:00:00')
const cysj=ref('')
const yq=ref('北京市第一人民医院-东院区')
const zyks=ref('综合住院部')
const fileInput = ref(null);
const avatarUrl = ref('');
let departmentOptions = ref([]);
const hospitalAreaOptions = ref([]);
const patientid= ref('')
// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};
const status = ref([{
  "label": "未支付",
  "value": "未支付"
}, {
  "label": "已支付",
  "value": "已支付"
}])
// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 创建文件URL并显示
    avatarUrl.value = URL.createObjectURL(file);

  }
};

const patientsList = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    operateTime: null,
    orderNo: null,
    patientName: null,
    zyid: null,
    source: null,
    bizType: null,
    payType: null,
    amount: null,
    payStatus: null,
    balance: null
  },
  rules: {
    orderNo: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    patientName: [
      { required: true, message: "患者姓名不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// watch(() => form.value.id, async (newValue, oldValue) => {
//   // 在这里执行你想要操作的
//   if (newValue) {
//     console.log(newValue)
//     form.value.medicalCardNumber=(await getPatients(newValue)).data.cardNo
//   }
// });
watch(() => form.value.hospitalArea, (newValue, oldValue) => {
  console.log('hospitalArea changed:', newValue);
  // 在这里执行你想要的操作，比如根据新的院区获取对应的科室
  if (newValue) {
    getDepartmentNames(newValue).then(response => {
      departmentOptions.value = response.data;
      getDepartmentsByhospitalArea(newValue).then(response => {
        console.log(response)
        departmentOptions = [];
        for (var i = 0; i < response.length; i++){
          departmentOptions.push(response[i].departmentName)
        }
      })
    });
  }
});
watch(() => form.value.patientName, (newValue, oldValue) => {
    if (typeof newValue=="number") {
      console.log(newValue)
      getPatients(newValue).then(response => {
        console.log(response)
        wxnc.value = response.data.wechatNickname
        jzrdz.value = response.data.address
        zjhm.value = response.data.idCard
        sj.value = response.data.phone
        patientid.value = newValue
        form.value.id=response.data.cardNo
        form.value.balance = response.data.cardBalance
      });
    }
    if(newValue==null){
      wxnc.value = ''
      jzrdz.value = ''
      zjhm.value = ''
      sj.value = ''
      patientid.value = ''
      form.value.balance = ''
      form.value.id= ''
    }
})
/** 查询住院充值记录列表 */
function getList() {
  loading.value = true
  listZyrecharge(queryParams.value).then(async response => {
    zyrechargeList.value = response.rows
    for (var i = 0; i < zyrechargeList.value.length; i++) {
      zyrechargeList.value[i].id = (await getPatients(zyrechargeList.value[i].patientName)).data.idCard
      zyrechargeList.value[i].balance = (await getPatients(zyrechargeList.value[i].patientName)).data.cardBalance
      zyrechargeList.value[i].patientName = (await getPatients(zyrechargeList.value[i].patientName)).data.name
    }
    total.value = response.total
    loading.value = false
    console.log(zyrechargeList.value)
  })
  listPatients().then( response => {
    patientsList.value = response.rows
  })
}
// 获取科室列表
function getDepartments() {
  getDepartmentNames().then(response => {
    departmentOptions.value = response.data
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 获取院区名称列表
function getHospitalAreas() {
  getHospitalCampusName().then(response => {
    for (let i = 0; i < response.length; i++) {
      hospitalAreaOptions.value.push(response[i].campusName);
    }
  });
}

// 表单重置
function reset() {
  form.value = {
    operateTime: null,
    orderNo: null,
    patientName: null,
    id: null,
    zyid: null,
    source: null,
    bizType: null,
    payType: null,
    amount: null,
    payStatus: null,
    balance: null,
    departmentId: null
  }
  proxy.resetForm("zyrechargeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加住院充值记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.zyid || ids.value
  getZyrecharge(_id).then(async response => {
    let a = {}
    form.value = response.data
    open.value = true
    title.value = "修改住院充值记录"
    a = await getPatients(form.value.patientName)
    wxnc.value = a.data.wechatNickname
    jzrdz.value = a.data.address
    zjhm.value = a.data.idCard
    sj.value = a.data.phone
    form.value.balance = a.data.cardBalance
    form.value.patientName = a.data.name
    patientid.value = a.data.id
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["zyrechargeRef"].validate(async valid => {
    if (valid) {
      form.value.patientName = patientid.value
      if (form.value.id != null) {
        if (form.value.ifok === 0 && form.value.payStatus === "已支付") {
            form.value.ifok = 1
            form.value.balance = form.value.balance + form.value.amount
            let a = await getPatients(patientid.value)
            a.data.cardBalance = form.value.balance
            await updatePatients(a.data)
            updateZyrecharge(form.value).then(response => {
              proxy.$modal.msgSuccess("修改成功")
              open.value = false
              getList()
            })
        } else {
          updateZyrecharge(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        }

      } else {
        addZyrecharge(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除住院充值记录编号为"' + _ids + '"的数据项？').then(function() {
    return delZyrecharge(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
/** 门诊消费记录序号 */
function rowFeeRecordsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 门诊消费记录添加按钮操作 */
function handleAddFeeRecords() {
  let obj = {}
  obj.patientName = ""
  obj.orderNo = ""
  obj.operateTime = ""
  obj.source = ""
  obj.bizType = ""
  obj.feeType = ""
  obj.payType = ""
  obj.amount = ""
  obj.payStatus = ""
  feeRecordsList.value.push(obj)
}

/** 门诊消费记录删除按钮操作 */
function handleDeleteFeeRecords() {
  if (checkedFeeRecords.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的门诊消费记录数据")
  } else {
    const feeRecordss = feeRecordsList.value
    const checkedFeeRecordss = checkedFeeRecords.value
    feeRecordsList.value = feeRecordss.filter(function(item) {
      return checkedFeeRecordss.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleFeeRecordsSelectionChange(selection) {
  checkedFeeRecords.value = selection.map(item => item.index)
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/zyrecharge/export', {
    ...queryParams.value
  }, `zyrecharge_${new Date().getTime()}.xlsx`)
}

getList()
getDepartments()
getHospitalAreas();
</script>
<style scoped>
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 10px;
}

.text {
  font-size: 15px;
  padding-right: 32px;
  padding-left: 10px;
  font-weight: 600;

}

.avatar-frame {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
  background-color: #E4EFFE;
}


.empty-frame {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #ccc;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>